package com.hnichr.ump.business.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hnichr.ump.business.Constant;
import com.hnichr.ump.common.doc.entity.Banner;
import com.hnichr.ump.common.doc.service.BannerService;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.system.service.impl.BaseServiceImpl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;

@Service
public class BannerServiceImpl extends BaseServiceImpl<Banner> implements BannerService {

	@Override
	@Transactional(readOnly = false)
	public Banner save(Banner banner) {
		// 验证商品是否已配置过
		Criteria criteria = Criteria.create();
		criteria.addCriterion("goodsId", Operator.EQ, banner.getGoodsId());
		List<Banner> banners = this.list(Banner.class, criteria);
		if (CollectionUtil.isNotEmpty(banners)) {
			throw new RuntimeException("该商品已配置过，请勿重复配置");
		}
		criteria = Criteria.create();
		criteria.addCriterion("seqNo", Operator.EQ, banner.getSeqNo());
		banners = this.list(Banner.class, criteria);
		if (CollectionUtil.isNotEmpty(banners)) {
			throw new RuntimeException("已存在相同配置的序号，请勿重复配置");
		}
		banner.setValidFlag(Constant.STATUS_VALID);
		super.save(banner);
		return banner;
	}

	@Override
	@Transactional(readOnly = false)
	public Banner update(Banner banner) {
		Banner old = this.getById(Banner.class, banner.getId());
		if (!StrUtil.equals(old.getGoodsId(), banner.getGoodsId())) {
			// 修改了展示的商品，校验新商品是否配置过
			Criteria criteria = Criteria.create();
			criteria.addCriterion("goodsId", Operator.EQ, banner.getGoodsId());
			List<Banner> banners = this.list(Banner.class, criteria);
			if (CollectionUtil.isNotEmpty(banners)) {
				throw new RuntimeException("该商品已配置过，请勿重复配置");
			}
		}
		JpaUtil.update(banner);
		return banner;
	}
}
